<?php

class Router{
  const URL_SEPARATOR = '/';
  
  protected $basePath = '';
  
  protected $URL;
  protected $parsedURL = array();  
  
  protected $module = 'default';
  protected $action = 'index';

  protected $parameters = array();
  protected $variables  = array();
  
  public function __construct(){
  }
  
  public function route($URL = null){
    $this->parseURL($URL);
    
    $partials = (array) explode(self::URL_SEPARATOR, trim($this->parsedURL['path'], self::URL_SEPARATOR));
    
    if(isset($partials[0]) && ctype_alnum($partials[0])){
      $this->module = array_shift($partials);
    }
    
    if(isset($partials[0]) && ctype_alnum($partials[0])){
      $this->action = array_shift($partials);
    }
    
    $this->parameters = $partials;
  }
  
  public function setBasePath($path){
    $this->basePath = $path;
  }
  
  public function getBasePath(){
    return $this->basePath;
  }

  public function setDefaultModule($module){
    $this->module = $module;
  }
  
  public function setDefaultAction($action){
    $this->action = $action;
  }
  
  protected function parseURL($URL){
    if($URL === null){
      $this->URL = $_SERVER['REQUEST_URI'] . '?' . $_SERVER['QUERY_STRING']; 
    }

    if(strpos($this->URL, $this->basePath) === 0){
      $this->URL = mb_substr($this->URL, mb_strlen($this->basePath));
    }
    
    $this->parsedURL = parse_url($this->URL);
  }
}